package com.wywah.core.filter;

import com.wywah.common.utils.ErrorUtils;
import com.wywah.core.propesties.CheckTokenProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.PathContainer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.pattern.PathPatternParser;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Objects;

/**
 * 校验系统服务令牌
 * 由于 Spring Cloud Gateway 区分了过滤器逻辑执行的“前”和“后”阶段（请参阅它是如何工作的），
 * 因此具有最高优先级的过滤器是“前”阶段中的第一个过滤器，而“后”阶段中的最后一个过滤器。
 */
@Configuration
@ConditionalOnProperty(value = "yunduo.check.token.enable")
public class CheckTokenGlobalFilter implements GlobalFilter, Ordered {
    private final CheckTokenProperties checkTokenProperties;
    private final PathPatternParser pattern = new PathPatternParser();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        boolean pass = false;
        for (String uri : checkTokenProperties.getWhitelist()) {
            if(pattern.parse(uri).matches(PathContainer.parsePath(request.getURI().getRawPath()))){
                pass = true;
                break;
            }
        }
        if(!pass){
            for (String key : checkTokenProperties.getCheckHeaderKeys()) {
                List<String> accessTokens = request.getHeaders().get(key);
                if(Objects.isNull(accessTokens)){
                    ErrorUtils.throwBaseException(String.format("[%s]不能为空", key));
                }
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -100;
    }

    public CheckTokenGlobalFilter(CheckTokenProperties checkTokenProperties) {
        this.checkTokenProperties = checkTokenProperties;
    }
}
